package com.icode.service.impl.management;

import com.icode.core.model.house.Assignment;
import com.icode.core.dto.manager.AssignmentDTO;
import com.icode.core.model.house.MyHouse;
import com.icode.core.model.house.MyHouseStatus;
import com.icode.core.model.user.User;
import com.icode.dao.AssignmentDao;
import com.icode.service.management.AssignmentService;
import org.hibernate.validator.jtype.TypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sunk
 * Date: 15-11-15
 * Time: 下午10:09
 * To change this template use File | Settings | File Templates.
 */
@Service("assignmentService")
@Transactional
public class AssignmentServiceImpl implements AssignmentService {
    @Autowired
    private AssignmentDao assignmentDao;

    @Override
    public void initAssignment(AssignmentDTO assignmentDTO) {
        String myHouseGuid = assignmentDTO.getMyHouseGuid();
        String description = assignmentDTO.getDescription();
        MyHouse myHouse = assignmentDao.findByGuid(MyHouse.class, myHouseGuid);
        myHouse.updateStatus(MyHouseStatus.TOASSIGNMNET);
        Assignment assignment = new Assignment(myHouse, description);
        assignmentDao.saveOrUpdate(assignment);
    }

    @Override
    public List<AssignmentDTO> getAssignments(String status) {
        MyHouseStatus myHouseStatus = MyHouseStatus.valueOf(status);
        List<Assignment> assignments = assignmentDao.findAssignmentByStatus(myHouseStatus);
        return AssignmentDTO.toDTOs(assignments);
    }

    @Override
    public void changeStatus(String assignmentGuid, String myHouseGuid) {
        Assignment assignment = assignmentDao.findByGuid(Assignment.class, assignmentGuid);
        MyHouse myHouse = assignmentDao.findByGuid(MyHouse.class, myHouseGuid);
        assignment.updateStatus(MyHouseStatus.ASSIGNMENTED);
        assignment.updateActive(false);
        myHouse.updateStatus(MyHouseStatus.ASSIGNMENTED);
    }

    @Override
    @Transactional
    public void setAssignmentsByMyHouseGuid(String myhouseguid, User user) {
        MyHouse myHouse = assignmentDao.findByGuid(MyHouse.class, myhouseguid);
        myHouse.updateStatus(MyHouseStatus.ASSIGNMENTED);
        Assignment assignment = assignmentDao.getAssignmentsByMyHouse(myHouse);
        //assignment.updateAssigner(user);
    }

    @Override
    public List<AssignmentDTO> findRentAllByPage(String currentPage, String status) {
        List<Assignment> assignments = assignmentDao.findRentAllByPage(currentPage, status);
        List<AssignmentDTO> assignmentDTOs = new ArrayList<>();
        if (assignments != null) {
            assignmentDTOs =AssignmentDTO.toDTOs(assignments);
        }
        return assignmentDTOs;
    }

}
